import Vue from 'vue'
import { get as getDictDetail } from '@/api/system/dictDetail'
import { JSortTable } from '@/utils/j-sortTable'

export const tablemixins = {

  data() {
    return {
      isShowTable: true,
      showPdf: false,
      pdfSrc: '',
      sort: {},
      isEditOrder: false,
      sortable: null, // 拖拽对象
      sortData: [], // 拖拽数据
      detailName: null,
      isSave: false,
      formInit: {},
      contextMenuData: {
        menuName: 'table',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: 'tableConfig', // 绑定事件
            icoName: 'el-icon-setting', // icon图标
            btnName: '表格设置' // 菜单名称
          },
          {
            fnHandler: 'copy', // 绑定事件
            icoName: 'el-icon-edit', // icon图标
            btnName: '复制' // 菜单名称
          }

        ]
      },
      tableConfigShow: false,
      rowIndex: -1
    }
  },
  // beforeCreate() {
  //   this.formInit = Object.assign({},defaultForm)
  // },
  activated() {
    try {
      if (this.$options.name.includes('Detail') || this.$options.name.includes('detail')) {
        if (this.$store.state.tagsView.exceptionList.includes(this.$route.name)) {
          return
        }
        const _form = JSON.parse(sessionStorage.getItem(this.detailName))
        if (!_form) {
          if (/add$/.test(window.location.href)) {
            sessionStorage.setItem('', this.detailName)
            return
          }
          return
        }
        this.$set(this.crud, 'order', _form)
        this.$set(this.crud, 'data', _form.detailList)
      }
    } catch (e) {
      this.crud.refresh()
    } finally {
      this.getList()
    }
  },

  deactivated() {
    if (this.$options.name.includes('Detail') || this.$options.name.includes('detail')) {
      if (this.$store.state.tagsView.exceptionList.includes(this.$options.name) || this.isSave) {
        return
      }
      let index = -1
      try {
        index = this.getTagsIndex()
      } catch (e) {
        return
      }
      if (index !== -1) {
        this.crud.order.detailList = this.crud.data
        this.detailName = this.$options.name + (this.crud.order.id || 'add')
        sessionStorage.setItem(this.detailName, JSON.stringify(this.crud.order))
      }
    }
  },
  mounted() {
    // this.getList()
  },
  computed: {},
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    // visitedViews() {
    //   return this.$store.state.tagsView.visitedViews
    // },
    setStorage() {
      this.crud.order.detailList = this.crud.data
      this.detailName = this.$options.name + (this.crud.order.id || 'add')
      sessionStorage.setItem(this.detailName, JSON.stringify(this.crud.order))
    },
    // 切换行索引
    switchRowIndex(row) {
      if (this.crud.order.orderStatus !== 'PASS') {
        if (row.index === this.rowIndex) {
          this.rowIndex = -1
          return
        }
        this.rowIndex = row.index
      }
    },
    getTagsIndex() {
      return this.visitedViews().findIndex(item => item.name + item.path.split('\/').slice(-1) === this.$options.name + (this.crud.order.id || 'add'))
    },
    async getList() {
      this.initSortable()
    },
    copyElement() {
      console.log('复制成功')
    },
    showMenu(event) {
      if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
        return
      }
      event.preventDefault()
      document.execCommand('copy')
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.contextMenuData.axis = {
        x, y
      }
    },
    tableConfig() {
      this.tableConfigShow = true
    },
    deletedata() {
    },
    pit() {
      this.crud.toUpdateHeader()
      this.handleCancelSort()
    },
    initSortable() {
      const th = this
      const el = document.querySelector('.el-table__header-wrapper thead tr')
      // 创建拖拽对象
      // JSortTable类创建
      new JSortTable(this.$refs.table, (evt) => {

        //原位置
        const oldIndex = th.crud.header.findIndex(item => evt.item.innerText === item.showName)
        //新位置
        const newIndex = th.crud.header.findIndex(item => evt.newNode.innerText === item.showName)

        const temp = th.crud.header[oldIndex]
        if (temp === null || temp === undefined) {
          return
        }
        th.crud.header.splice(oldIndex, 1)
        th.crud.header.splice(newIndex, 0, temp)
        th.crud.toUpdateHeader()
      }, false, this.$refs.table.bodyWrapper)

      // new Sortable(el, {
      //   onEnd(evt) {
      //     const { newIndex, oldIndex, item } = evt
      //     console.log(item)
      //     const noSort = [0, 1]
      //     if (noSort.includes(newIndex) || noSort.includes(oldIndex)) {
      //       return
      //     }
      //     // 获取原来title的name
      //     const oldtitle = item.children[0].innerHTML.match(/[^<]+/)[0]
      //     // 根据name获取所在的索引
      //     let thOldIndex =th.crud.header.findIndex(item=>item.showName === oldtitle)
      //     // 获取隐藏后的数组
      //     const list = th.crud.header.filter(item => item.visible === true)
      //     // 获取新位置所在的name值
      //     const newtitle = list[newIndex - 2].showName
      //     // 根据name获取所在的索引
      //     let thNewIndex = th.crud.header.findIndex(item=>item.showName === newtitle)
      //     const temp = th.crud.header[thOldIndex]
      //     if (temp === null || temp === undefined) {
      //       return
      //     }
      //     th.crud.header.splice(thOldIndex, 1)
      //     th.crud.header.splice(thNewIndex, 0, temp)
      //     th.crud.toUpdateHeader()
      //     th.handleCancelSort()
      //   }
      // })
    },
    handleCancelSort() {
      // 使table先隐藏，再显示，table将恢复拖拽之前的样式
      this.isShowTable = false
      setTimeout(() => {
        this.isShowTable = true
        // 必须延时，否则重新初始化的sortable无法拖拽
        setTimeout(() => {
          this.initSortable()
        }, 500)
      }, 100)
    },
    getDict(str) {
      try {
        return eval(str)
      } catch (e) {
        const w = str.split('.')
        w[0] = 'that'
        const n = str.split('.')[3].split('[')[0]
        if (!n) {
          return
        }
        const that = this
        this.queryDict(n).then(r => {
          return eval(w.join('.'))
        })

        // new Dict(this.dict).init(this.$options.dicts, () => {
        //   this.$nextTick(() => {
        //     this.$emit('dictReady')
        //   })
        // })
      }
    },
    async queryDict(n) {
      Vue.set(this.dict.dict, n, {})
      Vue.set(this.dict.label, n, {})
      Vue.set(this.dict, n, [])
      const that = this
      await getDictDetail(n).then(data => {
        const _data = data.data.content
        this.dict[n].splice(0, 0, ..._data)
        _data.forEach(d => {
          if (parseInt(d.value).toString() != 'NaN') {
            d.value = parseInt(d.value)
          }
          Vue.set(that.dict.dict[n], d.value, d)
          Vue.set(that.dict.label[n], d.value, d.label)
        })
      })
    },
    changeColWidth(nw, ow, col, evt) {
      const list = this.crud.header
      list.find(item => item.showName === col.label).width = nw
      this.crud.toUpdateHeader()
    },
    columnLabel(obj) {
      if (obj.showName) {
        return obj.showName
      }
      obj.showName = obj.label
      return obj.showName
    },
    tabSave() {
      this.tableConfigShow = false
      this.crud.toUpdateHeader()
      this.handleCancelSort()
    },
    sortTab(row, before) {
      if (row.column.order) {
        this.query.sort = `${before || 't'}.${row.column.property} ${row.column.order === 'ascending' ? 'asc' : 'desc'}`
        // this.sort[row.column.property] = row.column.order === 'ascending'?'asc':'desc'
      } else {
        try {
          this.query.sort = null
          // Reflect.deleteProperty(this.sort,row.column.property)
        } catch (e) {
          console.err(e)
        }
      }
      this.crud.toQuery()
    }
  }
}
